from django.contrib.auth.models import AbstractUser
from django.db import models
from django.http import JsonResponse
from itsdangerous import TimedJSONWebSignatureSerializer
from django.conf import settings


# Create your models here.
from meiduo001.utils.BaseModel import BaseModel


class User(AbstractUser):
    mobile = models.CharField(max_length=11,
                              unique=True,
                              )
    email_active = models.BooleanField(default=False,
                                      )

    class Meta:
        db_table = 'tb_users'

    def __str__(self):
        return self.username


    def generate_verify_email_url(self):
        obj = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,
                                              expires_in=3600 * 24)
        data = {'user_id': self.id,
                'email': self.email}
        token = obj.dumps(data).decode()
        verify_url = settings.EMAIL_VERIFY_URL + token
        return verify_url

    @staticmethod
    def check_verify_email_token(token):
        obj = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,
                                              expires_in=3600 * 24)
        try:
            data = obj.loads(token)

        except Exception as e:
            return JsonResponse({'code': 400,
                                 'errmsg': 'token无效'})
        id = data.get('user_id')
        email = data.get('email')

        try:
            user = User.objects.get(id=id,
                                    email=email)
        except Exception as e:
            return JsonResponse({'code':400,
                                 'errmsg':'获取对象失败'})
        return user


class Address(BaseModel):
    """
    用户地址
    """
    user = models.ForeignKey(User,
                             on_delete=models.CASCADE,
                             related_name='addresses'
                            )

    province = models.ForeignKey('areas.Area',
                                 on_delete=models.PROTECT,
                                 related_name='province_addresses',
                                 )

    city = models.ForeignKey('areas.Area',
                             on_delete=models.PROTECT,
                             related_name='city_addresses',
                            )

    district = models.ForeignKey('areas.Area',
                                 on_delete=models.PROTECT,
                                 related_name='district_addresses',
                                )

    title = models.CharField(max_length=20)
    receiver = models.CharField(max_length=20)
    place = models.CharField(max_length=50)
    mobile = models.CharField(max_length=11)
    tel = models.CharField(max_length=20,
                           null=True,
                           blank=True,
                           default=''
                          )

    email = models.CharField(max_length=30,
                             null=True,
                             blank=True,
                             default=''
                            )

    is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'tb_address'
